{
 "metadata": {
  "name": "",
  "signature": "sha256:9ea9e7c5821d8978bb4df4a4dfa5b8d7b788b8abb5e35a1fbe755c85491e0031"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "\"\"\"\n",
      "Example of creating a radar chart (a.k.a. a spider or star chart) [1]_.\n",
      "\n",
      "Although this example allows a frame of either 'circle' or 'polygon', polygon\n",
      "frames don't have proper gridlines (the lines are circles instead of polygons).\n",
      "It's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in\n",
      "matplotlib.axis to the desired number of vertices, but the orientation of the\n",
      "polygon is not aligned with the radial axes.\n",
      "\n",
      ".. [1] http://en.wikipedia.org/wiki/Radar_chart\n",
      "\"\"\"\n",
      "import numpy as np\n",
      "\n",
      "import matplotlib.pyplot as plt\n",
      "from matplotlib.path import Path\n",
      "from matplotlib.spines import Spine\n",
      "from matplotlib.projections.polar import PolarAxes\n",
      "from matplotlib.projections import register_projection\n",
      "\n",
      "\n",
      "def radar_factory(num_vars, frame='circle'):\n",
      "    \"\"\"Create a radar chart with `num_vars` axes.\n",
      "\n",
      "    This function creates a RadarAxes projection and registers it.\n",
      "\n",
      "    Parameters\n",
      "    ----------\n",
      "    num_vars : int\n",
      "        Number of variables for radar chart.\n",
      "    frame : {'circle' | 'polygon'}\n",
      "        Shape of frame surrounding axes.\n",
      "\n",
      "    \"\"\"\n",
      "    # calculate evenly-spaced axis angles\n",
      "    theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars)\n",
      "    # rotate theta such that the first axis is at the top\n",
      "    theta += np.pi/2\n",
      "\n",
      "    def draw_poly_patch(self):\n",
      "        verts = unit_poly_verts(theta)\n",
      "        return plt.Polygon(verts, closed=True, edgecolor='k')\n",
      "\n",
      "    def draw_circle_patch(self):\n",
      "        # unit circle centered on (0.5, 0.5)\n",
      "        return plt.Circle((0.5, 0.5), 0.5)\n",
      "\n",
      "    patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}\n",
      "    if frame not in patch_dict:\n",
      "        raise ValueError('unknown value for `frame`: %s' % frame)\n",
      "\n",
      "    class RadarAxes(PolarAxes):\n",
      "\n",
      "        name = 'radar'\n",
      "        # use 1 line segment to connect specified points\n",
      "        RESOLUTION = 1\n",
      "        # define draw_frame method\n",
      "        draw_patch = patch_dict[frame]\n",
      "\n",
      "        def fill(self, *args, **kwargs):\n",
      "            \"\"\"Override fill so that line is closed by default\"\"\"\n",
      "            closed = kwargs.pop('closed', True)\n",
      "            return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)\n",
      "\n",
      "        def plot(self, *args, **kwargs):\n",
      "            \"\"\"Override plot so that line is closed by default\"\"\"\n",
      "            lines = super(RadarAxes, self).plot(*args, **kwargs)\n",
      "            for line in lines:\n",
      "                self._close_line(line)\n",
      "\n",
      "        def _close_line(self, line):\n",
      "            x, y = line.get_data()\n",
      "            # FIXME: markers at x[0], y[0] get doubled-up\n",
      "            if x[0] != x[-1]:\n",
      "                x = np.concatenate((x, [x[0]]))\n",
      "                y = np.concatenate((y, [y[0]]))\n",
      "                line.set_data(x, y)\n",
      "\n",
      "        def set_varlabels(self, labels):\n",
      "            self.set_thetagrids(theta * 180/np.pi, labels)\n",
      "\n",
      "        def _gen_axes_patch(self):\n",
      "            return self.draw_patch()\n",
      "\n",
      "        def _gen_axes_spines(self):\n",
      "            if frame == 'circle':\n",
      "                return PolarAxes._gen_axes_spines(self)\n",
      "            # The following is a hack to get the spines (i.e. the axes frame)\n",
      "            # to draw correctly for a polygon frame.\n",
      "\n",
      "            # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`.\n",
      "            spine_type = 'circle'\n",
      "            verts = unit_poly_verts(theta)\n",
      "            # close off polygon by repeating first vertex\n",
      "            verts.append(verts[0])\n",
      "            path = Path(verts)\n",
      "\n",
      "            spine = Spine(self, spine_type, path)\n",
      "            spine.set_transform(self.transAxes)\n",
      "            return {'polar': spine}\n",
      "\n",
      "    register_projection(RadarAxes)\n",
      "    return theta\n",
      "\n",
      "\n",
      "def unit_poly_verts(theta):\n",
      "    \"\"\"Return vertices of polygon for subplot axes.\n",
      "\n",
      "    This polygon is circumscribed by a unit circle centered at (0.5, 0.5)\n",
      "    \"\"\"\n",
      "    x0, y0, r = [0.5] * 3\n",
      "    verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]\n",
      "    return verts\n",
      "\n",
      "\n",
      "def example_data():\n",
      "    #The following data is from the Denver Aerosol Sources and Health study.\n",
      "    #See  doi:10.1016/j.atmosenv.2008.12.017\n",
      "    #\n",
      "    #The data are pollution source profile estimates for five modeled pollution\n",
      "    #sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical species.\n",
      "    #The radar charts are experimented with here to see if we can nicely\n",
      "    #visualize how the modeled source profiles change across four scenarios:\n",
      "    #  1) No gas-phase species present, just seven particulate counts on\n",
      "    #     Sulfate\n",
      "    #     Nitrate\n",
      "    #     Elemental Carbon (EC)\n",
      "    #     Organic Carbon fraction 1 (OC)\n",
      "    #     Organic Carbon fraction 2 (OC2)\n",
      "    #     Organic Carbon fraction 3 (OC3)\n",
      "    #     Pyrolized Organic Carbon (OP)\n",
      "    #  2)Inclusion of gas-phase specie carbon monoxide (CO)\n",
      "    #  3)Inclusion of gas-phase specie ozone (O3).\n",
      "    #  4)Inclusion of both gas-phase speciesis present...\n",
      "    data = {\n",
      "        'column names':\n",
      "            ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO',\n",
      "             'O3'],\n",
      "        'Basecase':\n",
      "            [[0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],\n",
      "             [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],\n",
      "             [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],\n",
      "             [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],\n",
      "             [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]],\n",
      "        'With CO':\n",
      "            [[0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],\n",
      "             [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],\n",
      "             [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],\n",
      "             [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],\n",
      "             [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]],\n",
      "        'With O3':\n",
      "            [[0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],\n",
      "             [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],\n",
      "             [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],\n",
      "             [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],\n",
      "             [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]],\n",
      "        'CO & O3':\n",
      "            [[0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],\n",
      "             [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],\n",
      "             [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],\n",
      "             [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],\n",
      "             [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]]}\n",
      "    return data\n",
      "\n",
      "\n",
      "if __name__ == '__main__':\n",
      "    N = 9\n",
      "    theta = radar_factory(N, frame='polygon')\n",
      "\n",
      "    data = example_data()\n",
      "    spoke_labels = data.pop('column names')\n",
      "\n",
      "    fig = plt.figure(figsize=(9, 9))\n",
      "    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)\n",
      "\n",
      "    colors = ['b', 'r', 'g', 'm', 'y']\n",
      "    # Plot the four cases from the example data on separate axes\n",
      "    for n, title in enumerate(data.keys()):\n",
      "        ax = fig.add_subplot(2, 2, n+1, projection='radar')\n",
      "        plt.rgrids([0.2, 0.4, 0.6, 0.8])\n",
      "        ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),\n",
      "                     horizontalalignment='center', verticalalignment='center')\n",
      "        for d, color in zip(data[title], colors):\n",
      "            ax.plot(theta, d, color=color)\n",
      "            ax.fill(theta, d, facecolor=color, alpha=0.25)\n",
      "        ax.set_varlabels(spoke_labels)\n",
      "\n",
      "    # add legend relative to top-left plot\n",
      "    plt.subplot(2, 2, 1)\n",
      "    labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')\n",
      "    legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)\n",
      "    plt.setp(legend.get_texts(), fontsize='small')\n",
      "\n",
      "    plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',\n",
      "                ha='center', color='black', weight='bold', size='large')\n",
      "    plt.show()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [],
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}